<template>
  <div class="app">
    <div class="center" style="position: relative; top: 280px">
      <!-- 我喜欢按钮 -->
      <div class="rating-button" style="font-size: 30px">
        <i
            class="el-icon-star-off"
            :class="{ 'yellow-star': isLiked }"
            style="font-size: 30px; cursor: pointer;"
            @click="toggleLike"
        >
        </i>
        <span>我喜欢</span>

        <i
            class="el-icon-share"
            style="font-size: 30px; margin-left: 100px; cursor: pointer;"
            @click="openRatingModal"
        >
          <span>点击评分</span>
        </i>
      </div>
<!--      <el-button type="text">我喜欢</el-button>-->
<!--      <el-button type="text">评分</el-button>-->

      <!-- 评分模态框 -->
      <el-dialog title="评分" :visible.sync="ratingModalVisible" width="30%">
        <el-rate v-model="ratingValue" :max="5"></el-rate>
        <span slot="footer" class="dialog-footer">
          <el-button @click="ratingModalVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating">提交</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 歌曲介绍 -->
    <div class="introduction">
      <h2>歌曲详情:</h2>
      <div class="info">
        登入的用户id=> {{ userId }}
        <p>歌曲ID: {{ music.musicId }}</p>
        <p>歌曲名称: {{ music.musicName }}</p>
        <p>歌手: {{ music.singerStr }}</p>
        <p>单价: {{ music.musicPrice }}</p>
        <p>收藏数: {{ music.musicCollect }}</p>
        <p>销量: {{ music.musicSales }}</p>
        <p>发布时间: {{ music.musicCreateTime }}</p>
        <p>描述: {{ music.musicDesc }}</p>
      </div>
      <img v-if="music.musicImage" :src="music.musicImage" alt="Music Image"
           style="width: 200px; height: 200px; object-fit: cover;">
    </div>


    <!-- 歌词 -->
    <div class="lyrics">
      <h3>歌词:</h3>
      <pre>{{ music.musicWords }}</pre>
    </div>

    <!-- 播放按钮 -->
    <audio v-if="music.musicAudio" controls class="audio-player">
      <source :src="music.musicAudio" type="audio/mpeg">
      您的浏览器不支持 audio 元素。
    </audio>

    <!-- 评论详情 -->
    <div class="introduction">
      <h2>评论详情:</h2>
      <button @click="openDialog">添加评论</button>
      <el-radio-group v-model="commentView">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="mine">我的评论</el-radio-button>
      </el-radio-group>
      <el-table :data="filteredComments" style="width: 100%">
        <el-table-column prop="userName" label="用户昵称"></el-table-column>
        <el-table-column prop="commentContent" label="评论内容"></el-table-column>
        <el-table-column prop="commentCreateTime" label="评论时间"></el-table-column>
        <el-table-column label="操作" v-if="commentView === 'mine'">
          <template slot-scope="scope">
            <i class="el-icon-delete-solid" @click="deleteComment(scope.row)" style="font-size: 20px;"></i>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="comment.pageNum"
            :page-size.sync="comment.pageSize"
            :page-sizes="[1, 3, 5, 10]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
    </div>

    <!-- 添加评论模态框 -->
    <el-dialog title="添加评论" :visible.sync="dialogVisible" width="30%">
      <el-form :model="comment">
        <el-form-item label="评论内容">
          <el-input type="textarea" v-model="comment.commentContent"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import {getUserInfo} from "@/utils/auth";

export default {
  name: 'MainMusic',
  data() {
    return {
      isLiked: false, // 是否已点赞
      ratingModalVisible: false, // 控制评分模态框的显示
      ratingValue: null, // 评分值

      total: 0,
      userId: 0,
      musicId: 0,
      music: {},
      userInfo: {},
      comments: [], // 存储评论数据
      commentView: 'all', // 默认显示全部评论
      dialogVisible: false, // 控制模态框的显示
      comment: {
        pageNum: 1,
        pageSize: 5,
        commentMusicId: 0, // 音乐ID
        commentUserId: 0, // 用户ID
        commentContent: '', // 评论内容
        commentCreateTime: '', // 评论时间
      },
    };
  },
  computed: {
    filteredComments() {
      if (this.commentView === 'all') {
        return this.comments;
      } else if (this.commentView === 'mine') {
        return this.comments.filter(comment => comment.commentUserId === this.userId);
      } else {
        return [];
      }
    }
  },
  methods: {
    toggleLike() {
      this.isLiked = !this.isLiked;
    },
    openRatingModal() {
      this.ratingModalVisible = true;
    },
    submitRating() {
      console.log("提交的评分:", this.ratingValue);
      this.ratingModalVisible = false;
    },

    //----------
    deleteComment(row) {
      // 确认删除操作
      this.$confirm('确定要删除这条评论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 构建请求参数，传递调整后的时间、音乐ID和用户ID
        request({
          url: '/music/comment/web/delete',
          method: 'delete',
          params: {
            commentCreateTime: row.commentCreateTime, // 调整后的时间
            commentMusicId: row.commentMusicId,       // 评论的音乐ID
            commentUserId: row.commentUserId        // 评论的用户ID
          }
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.reviewDetails();
        }).catch(error => {
          console.error("删除评论失败:", error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(val) {
      this.comment.pageSize = val;
      this.reviewDetails();
    },
    handleCurrentChange(val) {
      this.comment.pageNum = val;
      this.reviewDetails();
    },
    openDialog() {
      this.dialogVisible = true;
      this.comment.commentMusicId = this.musicId;
      this.comment.commentUserId = this.userId;
    },
    submitComment() {
      this.comment.commentCreateTime = this.formatDate(new Date());
      console.log("提交的评论:", this.comment);
      request({
        url: '/music/comment/web/create',
        method: 'post',
        data: this.comment
      }).then(() => {
        this.reviewDetails();
        console.log("评论提交成功，重新获取评论数据");
      }).catch(error => {
        console.error("评论提交失败:", error);
      });
      this.dialogVisible = false;
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      const second = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    reviewDetails() {
      request({
        url: '/music/comment/web/list',
        method: 'get',
        params: {
          commentMusicId: this.musicId,
          pageNum: this.comment.pageNum,
          pageSize: this.comment.pageSize
        }
      }).then(res => {
        this.total = res.total;
        this.comments = res.rows.map(comment => ({
          ...comment,
          commentCreateTime: this.formatDate(new Date(comment.commentCreateTime))
        }));
        console.log("评论数据已更新:", this.comments);
      });
    },
    musicOne() {
      request({
        url: '/music/music/web/list',
        method: 'get',
        params: {musicId: this.musicId}
      }).then(res => {
        this.music = res.rows[0];
      });
    }
  },
  created() {
    this.musicId = localStorage.getItem('musicId');
    this.musicOne();
    this.userInfo = getUserInfo();
    this.userId = this.userInfo.userId;
    console.log("当前登录的用户 ID:", this.userId);
    this.reviewDetails();
  }
};
</script>
<style scoped> .app {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

.center {
  text-align: center;
}

.rating-button {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  font-size: 30px;
}

.rating-button i {
  margin-right: 8px;
}

.yellow-star {
  color: yellow;
}

.rating-button span {
  cursor: pointer;
}

.introduction {
  display: flex;
  flex-direction: column;
  width: 60%;
  margin-bottom: 20px;
}

.introduction .info {
  margin-bottom: 20px;
}

.lyrics {
  position: absolute;
  top: 60px;
  right: 20px;
  width: 30%;
  text-align: center;
}

.lyrics pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}

.audio-player {
  width: 100%;
  max-width: 600px;
  margin-top: 20px;
}

.lyrics[data-v-52f040bd] {
  text-align: left;
} </style>